package com.xinya.wanandroidclient.ui.tologin.login

import androidx.lifecycle.MutableLiveData
import com.xinya.wanandroidclient.base.BaseRepository
import com.xinya.wanandroidclient.bean.LoginBean
import com.xinya.wanandroidclient.eventbus.bean.LoginMessage
import com.xinya.wanandroidclient.http.ApiException
import com.xinya.wanandroidclient.http.RetrofitManager
import com.xinya.wanandroidclient.http.WanAndroidApiService
import com.xinya.wanandroidclient.utils.UserSPUtils
import kotlinx.coroutines.CoroutineScope
import org.greenrobot.eventbus.EventBus

/**
 *
 * @ClassName:      LoginRepo$
 * @Description:    java类作用描述
 * @Author:         xinya
 * @CreateDate:     2021/3/9$ 17:20$
 * @UpdateRemark:   更新内容
 * @Version:        1.0
 */
class LoginRepo(coroutineScope: CoroutineScope) : BaseRepository(coroutineScope) {
    fun login(
        username: String,
        password: String,
        loginLiveData: MutableLiveData<LoginBean>,
        errorLiveData: MutableLiveData<ApiException>,
    ) {
        launch(
            block = {
                RetrofitManager.getApiService(WanAndroidApiService::class.java)
                    .login(username, password).result()
            },
            success = {
                // sp保存
                UserSPUtils.INST.saveUser(it)
                // eventBus广播
                EventBus.getDefault().post(LoginMessage(it))
                loginLiveData.postValue(it)
            },
            error = {
                errorLiveData.postValue(it)
            }
        )
    }

}